Laboratory 2: Structures and Conditions.

Full name:

R#:

Title of the notebook:

Date:


Data Structures: List (Array)

A list is a collection of data that are somehow related. It is a convenient way to refer to a collection of similar things by a single name, and using an index (like a subscript in math) to identify a particular item.

Consider the "math-like" variable $x$ below:

\begin{gather} x_0= 7 \\ x_1= 11 \\ x_2= 5 \\ x_3= 9 \\ x_4= 13 \\ \dots \\ x_N= 223 \\ \end{gather}

The variable name is $x$ and the subscripts correspond to different values. Thus the value of the variable named $x$ associated with subscript $3$ is the number $9$.

The figure below is a visual representation of a the concept that treats a variable as a collection of cells.

In the figure, the variable name is MyList, the subscripts are replaced by an index which identifies which cell is being referenced. The value is the cell content at the particular index.

So in the figure the value of MyList at Index = 3 is the number 9.'

In engineering and data science we use lists a lot - we often call then vectors, arrays, matrices and such, but they are ultimately just lists.

To declare a list you can write the list name and assign it values. The square brackets are used to identify that the variable is a list. Like:

MyList = [7,11,5,9,13,66,99,223]

One can also declare a null list and use the append() method to fill it as needed.

MyOtherList = [ ]

Python indices start at ZERO. Alot of other lnguages start at ONE. Its just the convention.

The first element in a list has an index of 0, the second an index of 1, and so on. We access the contents of a list by referring to its name and index. For example

MyList[3] has a value of the number 9.

Data Structures: Special List | Tuple

A tuple is a special kind of list where the values cannot be changed after the list is created. It is useful for list-like things that are static - like days in a week, or months of a year. You declare a tuple like a list, except use round brackets instead of square brackets.

MyTupleName = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

Data Structures: Special List | Dictionary

A dictionary is a special kind of list where the items are related data PAIRS. It is a lot like a relational database (it probably is one in fact) where the first item in the pair is called the key, and must be unique in a dictionary, and the second item in the pair is the data. The second item could itself be a list, so a dictionary would be a meaningful way to build a database in Python.

To declare a dictionary using curly brackets

MyPetsNamesAndMass = { "Dusty":7.8 , "Aspen":6.3, "Merrimee":0.03}

To declare a dictionary using the dict() method

MyPetsNamesAndMassToo = dict(Dusty = 7.8 , Aspen = 6.3, Merrimee = 0.03)

Some examples follow:

Example: Nested Dictionary

From the dictionary below, print "Pandemic" and "Tokyo":


Conditional Execution

Conditional statements are logical expressions that evaluate as TRUE or FALSE and using these results to perform further operations based on these conditions. All flow control in a program depends on evaluating conditions. The program will proceed diferently based on the outcome of one or more conditions - really sophisticated AI programs are a collection of conditions and correlations. Amazon knowing what you kind of want is based on correlations of your past behavior compared to other peoples similar, butmore recent behavior, and then it uses conditional statements to decide what item to offer you in your recommendation items. It's spooky, but ultimately just a program running in the background trying to make your money theirs.

Conditional Execution: Comparison

The most common conditional operation is comparison. If we wish to compare whether two variables are the same we use the == (double equal sign).

For example x == y means the program will ask whether x and y have the same value. If they do, the result is TRUE if not then the result is FALSE.

Other comparison signs are != does NOT equal, < smaller than, >larger than, <=less than or equal, and >= greater than or equal.

There are also three logical operators when we want to build multiple compares (multiple conditioning); these are and, or, and not.

The and operator returns TRUE if (and only if) all conditions are TRUE. For instance 5 == 5 and 5 < 6 will return a TRUE because both conditions are true.

The or operator returns TRUE if at least one condition is true. If all conditions are FALSE, then it will return a FALSE. For instance 4 > 3 or 17 > 20 or 3 == 2 will return TRUEbecause the first condition is true. The not operator returns TRUE if the condition after the not keyword is false. Think of it as a way to do a logic reversal.

Conditional Execution: Block `if` statement


The if statement is a common flow control statement. It allows the program to evaluate if a certain condition is satisfied and to perform a designed action based on the result of the evaluation. The structure of an if statement is

if condition1 is met:
    do A
elif condition 2 is met:
    do b
elif condition 3 is met:
    do c
else:
    do e

The elif means "else if". The : colon is an important part of the structure it tells where the action begins. Also there are no scope delimiters like (), or {} . Instead Python uses indentation to isolate blocks of code.

This convention is hugely important - many other coding environments use delimiters (called scoping delimiters), but Python does not. The indentation itself is the scoping delimiter.

The next code fragment illustrates illustrates how the if statements work. The program asks the user for input. The use of raw_input() will let the program read any input as a string so non-numeric results will not throw an error. The input is stored in the variable named userInput. Next the statement if userInput == "1": compares the value of userInput with the string "1". If the value in the variable is indeed \1", then the program will execute the block of code in the indentation after the colon. In this case it will execute

print "Hello World"
print "How do you do? "

Alternatively, if the value of userInput is the string '2', then the program will execute

print "Snakes on a plane "

For all other values the program will execute

print "You did not enter a valid number"

Conditional Execution: Inline `if` statement

An inline if statement is a simpler form of an if statement and is more convenient if you only need to perform a simple conditional task. The syntax is:

do TaskA `if` condition is true `else` do TaskB

An example would be

myInt = 3
num1 = 12 if myInt == 0 else 13
num1

An alternative way is to enclose the condition in brackets for some clarity like

myInt = 3
num1 = 12 if (myInt == 0) else 13
num1

In either case the result is that num1 will have the value 13 (unless you set myInt to 0).

One can also use if to construct extremely inefficient loops.

Example: Pass or Fail?

Take the following inputs from the user:

1. Grade for Lesson 1 (from 0 to 5)
2. Grade for Lesson 2 (from 0 to 5)
3. Grade for Lesson 3 (from 0 to 5)

Compute the average of the three grades. Use the result to decide whether the student will pass or fail.


Here are some great reads on this topic:

Here are some great videos on these topics:


Exercise: Why dictionaries?

Why do we need to use dictionaries in python?

* Make sure to cite any resources that you may use.